<?php
namespace control;
/*
*物资采购申请类
*/

class materialPurchaseClass extends adIndexClass
{
    private const page = 'materialPurchase';
    private const table = 'resource_purchase';
    private const tableMx = 'resource_purchase_detail';
    private const title = '物资采购申请';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'      => [
                        'name'  => "{l.materialPurchase.homeSearch.orderNo}",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'staffId' => [
                        'name'  => "{l.materialPurchase.homeSearch.staffId}",
                        'width' => 300,
                    ],
                    'deptName'  => [
                        'name'  => "{l.materialPurchase.homeSearch.deptName}",
                        'width' => 300,
                    ],
                    'money'         => [
                        'name'  => '{l.materialPurchase.homeSearch.money}（' . static::$unit . '）',
                        'width' => 200,
                    ],
                    'recordDate'          => [
                        'name'  => '{l.materialPurchase.homeSearch.recordDate}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'    => [
                        'name'  => '{l.materialPurchase.homeSearch.state}',
                        'width' => 200,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('materialPurchase.home.orderNo') => text(array("name" => "orderNo")),
                    L('materialPurchase.home.deptName')     => text(array("name" => "deptName")),
                    L('materialPurchase.home.stid')   => selectMultiple(["name" => "stid", 'table' => 'staff', "sqlId" => 'stid', 'sqlField' => 'name']),
                ],
                [
                    L('materialPurchase.home.createTime') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    L('materialPurchase.home.state') => select(["name" => "state", 'option' => $this->stateOption]),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . L('materialPurchase.homeSearch.detail') . "','" . $url . "&fun=edit')\" class='spanButton'>" . L('materialPurchase.homeSearch.new') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('materialPurchase.homeSearch.del') . "</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//入库单号
            "deptName" => $this->post('deptName'),//供应商
        );
        //全等查询数组
        $equal = array(
            "staffId" => $this->post('stid'),//制单人
            "state" => $this->post('state'),//状态
        );
        $and = "";
        //如果没有查看所有员工请假记录的权限
        if (!$this->power(self::page, "seeAll")) {
            $and .= " and stid = '" . $this->control['stid'] . "' ";
        }
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => L('materialPurchase.homeSearch.edit'), "click" => "newIframe('" . L('materialPurchase.homeSearch.detail') . "','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => L('materialPurchase.homeSearch.detail'), "click" => "newIframe('" . L('materialPurchase.homeSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            if ($array['state'] != '草稿') {
                unset($dominate['edit']);
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "staffId":
                        $row[] = self::findStaff($array['staffId']);
                        break;
                    case "money":
                        $money = find(array('table' => self::tableMx, 'sum' => 'money', 'where' => "orderId = '$array[id]'"));
                        $row[] = $money;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx,
            'single' => "orderId in (select id from ".self::table." where 1=1 {$where})",
            'field'  => "ifnull(sum(money),0) as money",
        ]);
        $total    = [
            'money'        => self::lostZero($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();
        $info = query(self::table, " id = '" . $id . "' ");

        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => L('materialPurchase.edit.save'),
            "type" => "点击事件",
            "title" => L('materialPurchase.edit.save'),
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')"
        ];
        $tr[] = [
            '',
            '{l.materialPurchase.edit.materialName}',
            '{l.materialPurchase.edit.description}',
            '{l.materialPurchase.edit.num}',
            '{l.materialPurchase.edit.price}(' . static::$unit . ')',
            '{l.materialPurchase.edit.money}(' . static::$unit . ')',
            '{l.materialPurchase.edit.mxText}'
        ];
        $result = find(array(
            'field' => "id as mxId,name as materialName,description,num,price,money,text as mxText",
            'table' => self::tableMx." where orderId = '$info[id]' order by list"
        ));
        $totalArr = ['num'=>0,'money'=>0];
        if(count($result['array']) > 0) {
            foreach ($result['array'] as $k=>$array) {
                $array['list'] = $k+1;
                $tr[] = $this->purchaseRow($array);
                $totalArr['num'] += $array['num'];
                $totalArr['money'] += $array['money'];
            }
        }else{
            $tr[] = $this->purchaseRow(['mxId'=>self::getId(), 'list'=>1]);
        }
        $total = [
            3 => "<span id='total_num'>".self::lostZero($totalArr['num'],'numPrecision')."</span>",
            5 => "<span id='total_money'>".self::lostZero($totalArr['money'])."</span>",
        ];
        $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));

        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . L('materialPurchase.edit.staffId')."：" => selectMultiple(array("name" => "staffId",'value'=>$info['staffId'], "title" => "采购申请人", 'table' => 'staff', 'where' => "state !='离职'", "sqlId" => 'stid', 'sqlField' => 'name')),
                    must . L('materialPurchase.edit.recordDate')."：" => text(["name" => "recordDate", 'class' => 'text', 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    L('materialPurchase.edit.mxText')."：" => text(["name" => "text", 'class' => 'text', "value" => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => L('materialPurchase.edit.detailed'),
            'html' => $list,
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        //返回
        return $this->tab($data) . $this->js();
    }

    public function js(): string
    {
        return <<<eof
<script>
    //计算金额，税额等
    function countMoney(e){
        let price = $(e).parent().parent().find("[name='price[]']").val();
        let num = $(e).parent().parent().find("[name='num[]']").val();
        let money =(Number(price)*Number(num)).toFixed(amountPrecision);
        $(e).parent().parent().find(".money").html(money)
        calculateTotal()
    }
     //添加一行
     function addRow(e){
         $.post(root+'control/adIndex.html?cla=materialPurchase&fun=addRow',{},function (res){
             $(e).closest('tr').after(res.data);
             resetNumber($(e).closest('tbody'))
         },'json');
     }
     //计算总数量
    function calculateTotal(){
        let table = $('.editList')
        let num = 0,
        money = 0
        table.find("[name='num[]']").each(function(index){
            if($(this).val()){
              num+=Number($(this).val());
            }
            var moneyText = table.find(".money").eq(index).text()
            if(moneyText){
                money+=Number(moneyText);
            }
        })
        $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
        $("#total_money").text(money.toFixed(amountPrecision));
    }
</script>
eof;

    }

    /**
     * Desc : 物资采购明细
     * User : you name
     * Date : 2024-02-20 14:51
     * @param array $data
     * @return array|false|string
     */
    public function purchaseRow($data=[])
    {
        $list = isset($data['list'])?$data['list']:'';
        $mxId = isset($data['mxId'])&&$data['mxId']?$data['mxId']:self::getId();
        $field = ['materialName', 'description', 'num', 'price', 'money', 'mxText'];
        foreach ($field as $item){
            $array[$item] = isset($data[$item])?$data[$item]:$this->post($item);
        }
        unset($field[4]);
        $field = array_values($field);
        $cloneArg = json_encode([
            'cla' => 'materialPurchase',
            'fun' => 'purchaseRow',
            'copy' => $field,
            'nodeTextByClass' => ['money'],
        ],320);
        $delArg = json_encode([
            'empty' => $field,
            'emptyByClass' => ['money'],
        ],320);
        $tr = [
            componentClass::tablePperation($list, "delRows(this,$delArg);calculateTotal()","cloneRows(this,$cloneArg);calculateTotal()", "addRow(this)"),
            hidden(array('name' => 'mxId[]', 'value' => $mxId)) .
            text(array('name' => 'materialName[]', 'value' => $array['materialName'])),
            text(array('name' => 'description[]', 'value' => $array['description'])),
            text(array('name' => 'num[]','blur' => 'countMoney', 'value' => self::lostZero($array['num'],'numPrecision'), 'other' => self::digitalFiltering('numPrecision'))),
            text(array('name' => 'price[]','blur' => 'countMoney', 'value' => self::lostZero($array['price'],'pricePrecision'), 'other' => self::digitalFiltering('pricePrecision'))),
            "<span class='money'>".self::lostZero($array['money'])."</span>",
            text(array('name' => 'mxText[]', 'value' => $array['mxText']))
        ];
        if($data){
            return $tr;
        }
        $json['html'] = $this->tableMany(['tr' => [$tr], 'thead' => false]);
        return json_encode($json, 320);
    }

    /**
     *添加一行
     */
    public function addRow()
    {
        $res = json_decode($this->purchaseRow(),true);
        $html = $res['html'];
        $json['data'] = $html;
        return json_encode($json, 320);
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId') ?: [];
        $nameArr = $this->post('materialName');
        $numArr = $this->post('num');
        $priceArr = $this->post('price');
        $mxTextArr = $this->post('mxText');
        $descriptionArr = $this->post('description');

        $field = [
            'text' => $this->post('text'),
            'recordDate' => $this->post('recordDate'),
            'staffId' => $this->post('staffId'),
            'updateTime' => $this->time
        ];
        $annotation = [
            'staffId' => L('materialPurchase.editEdit.staffId'),
            'recordDate' => L('materialPurchase.editEdit.recordDate'),
        ];
        $rules = [
            'staffId' => 'required',
            'recordDate' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('materialPurchase.editEdit.power');
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = L('materialPurchase.editEdit.mxIdEmpty');
        } elseif (static::is_null_array($nameArr)) {
            $json['warn'] = L('materialPurchase.editEdit.nameEmpty');
        } elseif (static::is_null_array($numArr)) {
            $json['warn'] = L('materialPurchase.editEdit.numEmpty');
        } elseif (static::is_null_array($priceArr)) {
            $json['warn'] = L('materialPurchase.editEdit.priceEmpty');
        } elseif (!empty($info['id']) && $info['state'] != '草稿') {
            $json['warn'] = L('materialPurchase.editEdit.stateError');
        } else {
            $this->startTrans();
            $isPass = true;//事务通过标志
            if (!$info['id']) {

                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'WZSQ' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'deptName' => self::findStaffDepartment($this->control['stid']),
                    'state' => '草稿',
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }

            foreach ($mxIdArr as $k => $nid) {
                $mx = query(self::tableMx, "id = '$nid'");
                if (!empty($mx['id'])) {
                    //更新
                    $warn = static::update([
                        "table" => self::tableMx,
                        "field" => [
                            'name' => $nameArr[$k],
                            'num' => self::formattingFigure($numArr[$k],'numPrecision'),
                            'price' => self::formattingFigure($priceArr[$k],'pricePrecision'),
                            'money' => self::formattingFigure($numArr[$k] * $priceArr[$k], 'amount'),
                            'description' => $descriptionArr[$k],
                            'text' => $mxTextArr[$k],
                        ],
                        "where" => " id = '$nid'"
                    ]);
                } else {
                    //新增
                    $warn = static::insert([
                        "table" => self::tableMx,
                        "field" => [
                            'id' => $nid,
                            'orderId' => $id,
                            'name' => $nameArr[$k],
                            'num' => self::formattingFigure($numArr[$k],'numPrecision'),
                            'price' => self::formattingFigure($priceArr[$k],'pricePrecision'),
                            'money' => self::formattingFigure($numArr[$k] * $priceArr[$k], 'amount'),
                            'description' => $descriptionArr[$k],
                            'text' => $mxTextArr[$k],
                        ],

                    ]);
                }
                if (!in_array($warn, ['新增成功', '更新成功'])) {
                    $isPass = false;
                    $json['warn'] = $warn;
                    break;
                }
            }

            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                $this->commitTrans();
                delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text =str_replace(['{{staffName}}','{{type}}','{{id}}'], [$this->control['name'],$type,$id], L('materialPurchase.editEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
          if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'],'selfChoose')) {
            $button[] = [
                "name" => L('salesContract.auditButton.start'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => '物资采购申请',
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        // 保存函数
                        'save' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'editEdit'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => L('salesContract.auditButton.addApprover'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => L('salesContract.auditButton.transfer'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => L('salesContract.auditButton.approval'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => L('salesContract.auditButton.cancel'),
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('materialPurchase.detail.empty');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => L('materialPurchase.detail.detail'),
            );

            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => L('materialPurchase.detail.edit'),
                    "type" => "顶部页卡",
                    "title" => L('materialPurchase.detail.editDetail'),
                    "url" => $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=edit&id=' . $info['id'],

                ];
            }
            if ($this->power(self::page, "del") && $info['state'] == '草稿'){
                //按钮
                $button[] = [
                    "name" => L('materialPurchase.detail.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            //审核按钮
            $button = array_merge($button, $this->auditButton($info));

            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list asc"));
            $tr[] = ['{l.materialPurchase.edit.materialName}', '{l.materialPurchase.edit.description}', '{l.materialPurchase.edit.num}', '{l.materialPurchase.edit.price}(' . static::$unit . ')', '{l.materialPurchase.edit.money}(' . static::$unit . ')', '{l.materialPurchase.edit.mxText}'];
            foreach ($result['array'] as $index => $val) {
                $tr[] = [$val['name'], $val['description'], self::lostZero($val['num'],'numPrecision'), self::lostZero($val['price'],'pricePrecision'), self::lostZero($val['money'],'amount'), $val['text']];
            }
            $total = find(array(
                'table'  => self::tableMx,
                'field'  => "ifnull(sum(num),0) as num,ifnull(sum(money),0) as totalMoney",
                'single' => "orderId = '$info[id]' order by list asc"
            ));
            $total_tr = [
                2=>self::lostZero($total['num'], 'numPrecision'),
                4=>self::lostZero($total['totalMoney']),
            ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "详细信息" => array(
                    array(
                        L('materialPurchase.detail.staffId') => self::findStaff($info['staffId']),
                        L('materialPurchase.detail.deptName') => $info['deptName'],
                        L('materialPurchase.detail.recordDate') => $info['recordDate'],
                        L('materialPurchase.detail.orderNo') => $info['orderNo'],
                    ),
                    array(
                        L('materialPurchase.detail.stid') => self::findStaff($info['stid']),
                        L('materialPurchase.detail.state') => $info['state'],
                    ),
                    array(
                        L('materialPurchase.detail.text') => pre($info['text']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => L('materialPurchase.detail.purchaseMx'),
                'html' => $this->listTable(array('tr' => $tr, 'total' => $total_tr, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailBlock([
                L('materialPurchase.detail.process') => auditClass::auditRecord(self::table, $info['id'])
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = L('materialPurchase.operate.del');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('materialPurchase.operate.warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }



    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('materialPurchase.delete.power');
        } elseif (empty($array)) {
            $json['warn'] = L('materialPurchase.delete.noChoice');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = L('materialPurchase.delete.fail');
                } else {
                    $all = find(array('table'=>'file','where'=>"targetId = '$id'"));
                    foreach ($all['array'] as $val){
                        fileDelete($val['src']);
                        delete(array("table" =>'file', "where" => " id = '$val[id]' "));
                    }
                    delete(array('table'=>'audit','where'=>"targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));

                    //返回
                    $warn = L('materialPurchase.delete.success');
                    $x++;
                }
                $text .= str_replace(['{{id}}'], [$info['id']], L('materialPurchase.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('materialPurchase.delete.log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('materialPurchase.delete.warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 删除明细
     * @return bool|string
     */
    public function deleteMx()
    {
        $array = $this->post('mxId');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('materialPurchase.deleteMx.power');
        } elseif (empty($array)) {
            $json['warn'] = L('materialPurchase.deleteMx.noChoice');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $mx = query(self::tableMx, " id = '$id' ");
                $material = query('resource', " id = '$mx[sourceId]' ");
                //最后删除基本参数
                delete(array("table" => self::tableMx, "where" => " id = '$id' "));
                //返回
                $warn = L('materialPurchase.deleteMx.success');
                $x++;
                $text .= str_replace(['{{materialName}}','{{id}}'], [$material['name'],$mx['id']], L('materialPurchase.deleteMx.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('materialPurchase.deleteMx.log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('materialPurchase.deleteMx.warn'));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }
}

